package com.mmsj;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;


/**
 * @author ChuXuan
 */
public class MenuListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_list);

        ListView listView = findViewById(R.id.list_view);
        List<Menu> menuList = new ArrayList<>();

        // 数据初始化
        SQLiteDatabase db = MyDBHelper.getInstance(this).getWritableDatabase();
        // 使用 try-with-resources 自动关闭 Cursor
        try (Cursor cursor = db.rawQuery("select * from menu", null)) {
            int count = cursor.getCount();
            if (count > 0) {
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(0);
                    String name = cursor.getString(1);
                    String description = cursor.getString(2);
                    double price = cursor.getDouble(3);
                    Menu menu = new Menu(id, name, description, price);
                    menuList.add(menu);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建适配器
        MenuAdapter adapter = new MenuAdapter(MenuListActivity.this,menuList);
        listView.setAdapter(adapter);

    }
}